package com.whg.demo.exception;

import com.whg.demo.model.JsonData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author whg
 * @create 2022/12/1 14:45
 * @description：
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 捕获全局异常，处理所有不可知的异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    //@ResponseBody
    public JsonData handleException(Exception e, HttpServletRequest request){
        logger.error("url： {} , msg： {}",request.getRequestURL(),e.getMessage());
        return JsonData.buildError(request.getRequestURL(),e.getMessage());
    }

    /**
     * 处理自定义异常（进行页面跳转）
     * @param e
     * @return
     */
    /*@ExceptionHandler(value = MyException.class)
    public ModelAndView handleMyException(MyException e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error.html");
        modelAndView.addObject("msg",e.getMsg());
        return modelAndView;
    }*/


    /**
     * 处理自定义异常（不进行页面跳转）
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    public JsonData handleMyException(MyException e){
        return JsonData.buildError(e.getMsg(),e.getCode());
    }
}
